package se.ytterman.jpcap;

import java.lang.*;
import java.io.*;
import java.util.*;

import se.ytterman.jpcap.io.PcapPacketInputStream;
import se.ytterman.jpcap.io.PcapPacketOutputStream;
import se.ytterman.jpcap.jni.PcapInterface;
import se.ytterman.jpcap.jni.PcapSocket;
import se.ytterman.jpcap.pcap.PcapPacket;

public class PcapListenerThread extends Thread {

    public PcapListenerThread(PcapInterface pcapInterface,
			      String pcapFilter) {
	// Set terminate flag
	this.terminate = false;

	// Create socket reference
	this.pcapSocket = pcapInterface.getSocketOnInterface();

	// Set pcap filter on socket
	this.pcapSocket.setFilter(pcapFilter);
    }

    // XXX add finalizer

    // Overloading run() in java.lang.Thread
    public void run() {
	// Loop forever
	while(!this.terminate) {
	    try {
		// Create new packet
		PcapPacket pcapPacket = new PcapPacket();
	
		// Read from socket
		this.pcapSocket.read(pcapPacket);

		// Debug...
		if(false) {
		    pcapPacket.printHexdump(System.out);
		}

		// Create a data input stream
		PcapPacketInputStream packetInputStream = 
		    new PcapPacketInputStream(pcapPacket);

		// Call overloaded parser function
		// this.parse(packetInputStream);

		// Call overloaded content handler function
	    }
	    catch(Exception e) {
		// XXX Yepp, we should catch some here...
	    }
	}
    }

    public void terminate() {
	// Set terminate flag
	this.terminate = true;
    }

    // Class reference to a pcap socket
    protected PcapSocket pcapSocket;

    // Thread termination flag
    private boolean terminate; 
}
